import { useState } from 'react'
import { LoadMore } from '@mf2e/bamboo-ui-rn'

const useLoadMore = (onFetch, enabled) => {
  const [state, setState] = useState(null)

  const onEndReached = async () => {
    if (state === 'loading' || state === 'finish') return

    setState('loading')
    try {
      const isFinish = await onFetch?.()
      setState(isFinish ? 'finish' : null)
    } catch (e) {
      console.log(e)
      setState('fail')
    }
  }

  const ListFooterComponent = () => {
    return <LoadMore state={state} onRetry={onEndReached} />
  }

  return enabled
    ? {
        onEndReached,
        onEndReachedThreshold: 0.2,
        ListFooterComponent,
      }
    : {}
}

export default useLoadMore
